package com.apes.enquiry.supplier.baturu;

import com.alibaba.fastjson.JSONObject;
import com.apes.enquiry.supplier.SupplierInterfaceApi;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.esb.processor.connector.http.HttpTransporter;
import com.apes.framework.util.MapUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class BaturuApi extends SupplierInterfaceApi {

    @Value("${baturu.url}")
    private String HOST;
    @Value("${baturu.appKey}")
    private String APP_KEY;
    @Value("${baturu.secretKey}")
    private String SECRET_KEY;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取 token
     */
    public String getToken() {
        String token = stringRedisTemplate.opsForValue().get("baturn_token");
        if (!StringUtils.isEmpty(token)) return token;

        String method = "/open/auth/v1/getAccessToken";
        long timestamp = System.currentTimeMillis();
        String secretKeyDigest = calcSecretKeyDigest(SECRET_KEY, timestamp);

        // 构建传入参数
        Map body = MapUtil.mapper("appkey", APP_KEY, "secretKeyDigest", secretKeyDigest);
        Map header = MapUtil.mapper("timestamp", String.valueOf(timestamp));
        JSONObject json = execute(HOST + method, body, header, "POST");     // 执行请求
        token = json.getString("model");
        if (StringUtils.isEmpty(token)) throw new RuntimeException("调用巴图鲁接口获取token失败，请检查！");

        // 巴图鲁的 token 有效期为 10天，这里设置 10天
        stringRedisTemplate.opsForValue().set("baturn_token", token, 9, TimeUnit.DAYS);
        return token;
    }

    /**
     * 发布询价
     */
    public JSONObject publishInquire(Map body) {
        String method = "/open/trade/v1/publishInquiry";
        return executePost(HOST + method, body, getHeader());
    }


    /**
     * 获取报价结果
     */
    public JSONObject queryQuote(JSONObject body) {
        String method = "/open/trade/v1/queryQuote";
        method += "?userKey=" + body.getString("userKey") + "&inquiryNo=" + body.getString("inquiryNo") + "&invoiceType=" + body.getInteger("invoiceType");
        return executeGet(HOST + method, body, getHeader());
    }

    /**
     * 查询供应商承运商
     */
    public JSONObject queryCarrier(JSONObject body) {
        String method = "/open/trade/v1/queryCarrier";
        return executePost(HOST + method, body, getHeader());
    }

    /**
     * 查询供应商承运商
     */
    public JSONObject addCart(JSONObject body) {
        String method = "/open/trade/v1/addCart";
        return executePost(HOST + method, body, getHeader());
    }

    /**
     * 创建订单
     */
    public JSONObject createOrder(JSONObject body) {
        String method = "/open/trade/v1/createOrder";
        return executePost(HOST + method, body, getHeader());
    }

    /**
     * 支付
     */
    public JSONObject pay(JSONObject body) {
        String method = "/open/trade/v2/pay";
        return executePost(HOST + method, body, getHeader());
    }

    public JSONObject confirmReceipt(JSONObject body) {
        String method = "/open/trade/v1/confirmReceipt";
        return executePost(HOST + method, body, getHeader());
    }

    /**
     * 车架号获取车型信息
     * @param body 请求体
     * @return
     */
    public JSONObject queryCarTypeByVin(JSONObject body){
        String method = "/open/car/queryCarTypeByVin";
        return executePost(HOST + method, body, getHeader());
    }

    /**
     * 根据 vin 码和配件别名查询配件标准名称
     * @param body 请求体
     * @return
     */
    public JSONObject searchPartsHintsInfo(JSONObject body){
        String method = "/open/parts/searchPartsHintsInfo";
        return executePost(HOST + method, body, getHeader());
    }

    /**
     * 根据 vin+配件名称带出epc图片、OE号等信息
     * @param body
     * @return
     */
    public JSONObject queryPartsCodeInfo(JSONObject body){
        String method = "/open/parts/queryPartsCodeInfo";
        return executePost(HOST + method, body, getHeader());
    }

    /**
     * 替换编码接口
     * @param body
     * @return
     */
    public JSONObject queryPartsReplaceCode(JSONObject body){
        String method = "/open/parts/queryPartsReplaceCode";
        return executePost(HOST + method, body, getHeader());
    }

    /**
     * 查询4s价格
     * @param body
     * @return
     */
    public JSONObject query4sPrice(JSONObject body){
        String method = "/open/parts/price/query4sPrice";
        return executePost(HOST + method, body, getHeader());
    }

    private JSONObject getHeader() {
        return (JSONObject) JSONObject.toJSON(MapUtil.mapper("accessToken", getToken(), "timestamp", String.valueOf(System.currentTimeMillis())));
    }

    /**
     * 计算密钥摘要
     *
     * @param secretKey 应用密钥, 由巴图鲁分配
     * @param timestamp 当前时间戳, 生成示例: System.currentTimeMillis()
     */
    private String calcSecretKeyDigest(String secretKey, long timestamp) {
        // 将当前时间戳与应用密钥拼接组合
        String tempStr = timestamp + secretKey;
        // 传入组合后的字符串调用 DigestUtils.sha256Hex(); 计算密钥摘要
        return DigestUtils.sha256Hex(tempStr);
    }


}
